<template>
  <div class="profile-settings">
    <n-h3 prefix="bar">个人资料</n-h3>
    <div>
      <n-form-item label="姓名">
        <n-input v-model:value="form.name" placeholder="姓名" />
      </n-form-item>
      <n-form-item label="手机号">
        <n-input v-model:value="form.telephone" placeholder="手机号" />
      </n-form-item>
      <n-form-item label="电子邮箱">
        <n-input v-model:value="form.mail" placeholder="电子邮箱" />
      </n-form-item>
      <n-form-item label="个人简介">
        <n-input v-model:value="form.intro" type="textarea" placeholder="个人简介" maxlength="140" show-count />
      </n-form-item>
      <n-button type="primary" @click="update" :loading="requesting" :disabled="requesting">更新资料</n-button>
    </div>
  </div>
</template>

<script setup>
import {ref} from "vue";
import {useUserStore} from "@/stores/user.js";
import {useRequests} from "@/common/requests.js";
import {useMessage, useNotification} from "naive-ui";

const userStore = useUserStore()
const requests = useRequests()
const message = useMessage()
const notify = useNotification()

const form = ref({
  name: userStore?.profile?.name,
  telephone: userStore?.profile?.telephone,
  mail: userStore?.profile?.mail,
  intro: userStore?.profile?.intro,
})

const requesting = ref(false)
const update = () => {
  requesting.value = true
  requests.profile.update(form.value).then(resp => {
    requesting.value = false
    if (resp.ret === 0) {
      requests.profile.getMe().then(resp => {
        if (resp.ret === 0) {
          userStore.$patch({profile: resp.data})
        }
      })

      message.success("更新成功")
    } else {
      message.error(resp?.data ?? resp?.msg ?? "未知错误")
    }
  }).catch(err => {
    requesting.value = false

    console.log(err)
    notify.error({content: "出错了", meta: err.toString(), duration: 1500})
  })
}
</script>
